import { defineStore } from 'pinia'
import { getToken, removeToken, setToken } from '../utils/token-utils'
import type { UserInfoState } from './interface'
import { ElMessage } from 'element-plus'
import { staticRoutes } from '@/router/routes'
import allRouter from '@/data/db.json'
import router from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import { defineAsyncComponent } from 'vue'
import Layout from '@/layout/index.vue'
import showView from '@/views/Survey/TopicList/index.vue'
import { reqGetUserInfo, reqUserLogin } from '@/api/login'
// 根据映射来查找组件对应的模块

// 处理后台返回的路由
const useUserRouter = (allRouterList: any) => {
  const mapRoutersList = allRouterList.map((item: any, index: number) => {
    if (item.component && item.component === 'Layout') {
      item.component = Layout
    } else {
      const path = `@/views/${item.component}/index.vue`
      item.component = showView
    }
    if (item.children && item.children.length !== 0) {
      item.children = useUserRouter(item.children)
    }
    return item
  })
  return mapRoutersList
}
// 重组路由处理后台返回的数据格式
// function generateIndexRouter(data: any) {
//   var routesChildren = generateChildRouters(data)
//   const formatRouter = (routes: any, newRoutes = []) => {
//     routes.map((item: any) => {
//       if (item.children && item.children.length > 0)
//         formatRouter(item.children, newRoutes)
//       //console.log(item);
//       if (item.path != '') {
//         newRoutes.push(item)
//       }
//     })
//     return newRoutes
//   }
//   let flatRoutes = formatRouter(routesChildren)
//   console.log('flatRoutes', flatRoutes)

//   //router.addRoutes(flatRoutes);
//   let indexRouter = [
//     {
//       path: '/',
//       name: 'dashboard',
//       component: () => import('@/layout/index.vue'),
//       meta: { title: '首页' },
//       redirect: '/home/dashboard',
//       children: flatRoutes
//     }
//   ]
//   return indexRouter
// }

// // 生成嵌套路由（子路由）

// function generateChildRouters(data: any) {
//   const routers = []
//   for (var item of data) {
//     // console.log(data, 'data---------------------');
//     let component = ''
//     if (item.component.indexOf('Layout') >= 0) {
//       console.log('jinlail')
//       component = 'views/layout/layout-sub'
//     } else {
//       component = 'views/' + item.component
//     }

//     // eslint-disable-next-line
//     // let URL = (item.meta.url || '').replace(/{{([^}}]+)?}}/g, (s1, s2) =>
//     //   eval(s2)
//     // ) // URL支持{{ window.xxx }}占位符变量
//     // if (isURL(URL)) {
//     //   item.meta.url = URL
//     // }
//     const path = `@/views/${item.component}/index.vue`
//     let menu = {
//       path: item.path,
//       name: item.name,
//       redirect: item.redirect,
//       component: path,
//       hidden: item.hidden,
//       //component:()=> import(`@/views/${item.component}.vue`),
//       meta: {
//         title: item.meta.title,
//         icon: item.meta.icon,
//         url: item.meta.url,
//         permissionList: item.meta.permissionList,
//         keepAlive: item.meta.keepAlive
//       }
//     }
//     // console.log(menu, '0000000000000000000000000');
//     let menuSub
//     if (item.alwaysShow) {
//       menu.alwaysShow = true
//       menu.redirect = menu.path
//     }
//     if (item.children && item.children.length > 0) {
//       menu.children = [...generateChildRouters(item.children)]
//     }
//     //--update-begin----author:scott---date:20190320------for:根据后台菜单配置，判断是否路由菜单字段，动态选择是否生成路由（为了支持参数URL菜单）------
//     //判断是否生成路由
//     if (item.route && item.route === '0') {
//       //console.log(' 不生成路由 item.route：  '+item.route);
//       //console.log(' 不生成路由 item.path：  '+item.path);
//     } else {
//       routers.push(menu)
//       //routers.push(menu.children);
//     }
//     //--update-end----author:scott---date:20190320------for:根据后台菜单配置，判断是否路由菜单字段，动态选择是否生成路由（为了支持参数URL菜单）------
//   }
//   // console.log(routers, '--------wwwwwwwww------------');
//   return routers
// }

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

  actions: {
    async login(username: string, password: string) {
      const res = await reqUserLogin(username, password)
      if (res.code === 20000) {
        // 登录成功,将token存储到本地
        setToken(res.data.token)
        this.token = res.data.token
        Promise.resolve(true)
      } else {
        Promise.reject(false)
      }
    },

    async getUserInfo() {
      const res = await reqGetUserInfo()
      // console.log(res, '获取成功')
      if (res.code === 20000) {
        this.name = res.data.name
        this.avatar = res.data.avatar
        console.log(res.data.routes)
        // const newRoute = generateIndexRouter(res.data.routes.router)
        // // console.log(newRoute)
        // const resone = newRoute.filter((item, index) => {
        //   return item.path == '/'
        // })
        // resone.forEach((item, index) => {
        //   if (item.children && item.children.length > 0) {
        //     item.children.forEach((item1, index) => {
        //       router.addRoute(item1)
        //     })
        //   }
        //   router.addRoute(item)
        // })
        // console.log(resone[0].children, 'sssssssssssssssssssss')
        // this.menuRoutes = resone[0].children
        const lastRouterView = useUserRouter(res.data.routes)
        console.log(lastRouterView)
        lastRouterView.forEach((item: any, index: number) => {
          // console.log(item)
          router.addRoute(item)
        })
        // console.log(lastRouterView, ';1122222222222')

        this.menuRoutes = staticRoutes.concat(lastRouterView)
        Promise.resolve(true)
      } else {
        Promise.reject(false)
      }
    },

    reset() {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    }
  }
})
